package com.zzyl.nursing.service.impl;

import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.json.JSONUtil;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备管理Service业务层处理
 *
 * @author ruoyi
 * @date 2024-12-13
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private Client client;
    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询设备管理
     *
     * @param id 设备管理主键
     * @return 设备管理
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备管理列表
     *
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备管理
     *
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备管理
     *
     * @param dto 设备管理
     * @return 结果
     */
    @Override
    @Transactional
    public int updateDevice(Device dto) {
        // 查询该设备是否存在
        LambdaQueryWrapper<Device> qu = Wrappers.<Device>lambdaQuery().eq(Device::getId, dto.getId());
        Device oldDevice = deviceMapper.selectOne(qu);
        if (ObjectUtils.isEmpty(oldDevice)) {
            throw new BaseException("该设备不存在！");
        }
        //如果两个备注昵称不相同，则去更新物联网平台
        if (!Objects.equals(oldDevice.getNickname(), dto.getNickname())) {
            BatchUpdateDeviceNicknameRequest res = new BatchUpdateDeviceNicknameRequest();
            List<BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo> deviceNicknameInfo = new ArrayList<>();
            BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo batchUpdateDeviceNicknameRequestDeviceNicknameInfo
                    = new BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo();

            batchUpdateDeviceNicknameRequestDeviceNicknameInfo.setProductKey(dto.getProductKey());
            batchUpdateDeviceNicknameRequestDeviceNicknameInfo.setDeviceName(dto.getDeviceName());
            batchUpdateDeviceNicknameRequestDeviceNicknameInfo.setNickname(dto.getNickname());
            deviceNicknameInfo.add(batchUpdateDeviceNicknameRequestDeviceNicknameInfo);
            res.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
            res.setDeviceNicknameInfo(deviceNicknameInfo);
            BatchUpdateDeviceNicknameResponse resp;
            try {
                resp = client.batchUpdateDeviceNickname(res);
            } catch (Exception e) {
                throw new BaseException("修改设备备注昵称失败！");
            }
            if (!resp.getBody().success) {
                new BaseException("修改设备备注昵称失败！");
            }
        }
        if (dto.getLocationType().equals(0)) {
            dto.setPhysicalLocationType(-1);
        }
        return updateById(dto) ? 1 : 0;
    }

    /**
     * 批量删除设备管理
     *
     * @param ids 需要删除的设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备管理信息
     *
     * @param id 设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 从物联网平台同步产品列表 保存到redis
     */
    @Override
    public void syncProductList() {
        QueryProductListResponse queryProductListResponse;
        try {
            QueryProductListRequest queryProductListRequest = new QueryProductListRequest();
            // 分页条件
            queryProductListRequest.setPageSize(200);
            queryProductListRequest.setCurrentPage(1);
            // 公共实例
            queryProductListRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
            // 查询公共实例下的所有产品
            queryProductListResponse = client.queryProductList(queryProductListRequest);
        } catch (Exception e) {
            throw new BaseException("同步产品列表失败");
        }
        if (!queryProductListResponse.getBody().success) {
            throw new BaseException("同步产品列表失败");
        }
        // 转成json
        String jsonStr = JSONUtil.toJsonStr(queryProductListResponse.getBody().getData().getList().getProductInfo());
        // 保存到redis
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_ALL, jsonStr);
    }

    /**
     * 从redis中获取产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        String jsonStr = (String) redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_ALL);
        if (StringUtils.isEmpty(jsonStr)) {
            return Collections.emptyList();
        }
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }

    /**
     * 删除设备
     *
     * @param device
     */
    @Override
    @Transactional
    public void deleteDevice(Device device) {
        LambdaQueryWrapper<Device> qu = Wrappers.<Device>lambdaQuery()
                .eq(Device::getIotId, device.getIotId());
        int i = deviceMapper.delete(qu);
        if (i <= 0) {
            throw new BaseException("设备不存在!");
        } else {
            DeleteDeviceRequest request = new DeleteDeviceRequest();
            request.setDeviceName(device.getDeviceName());
            request.setProductKey(device.getProductKey());
            request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
            request.setIotId(device.getIotId());
            DeleteDeviceResponse response;
            try {
                response = client.deleteDevice(request);
            } catch (Exception e) {
                throw new BaseException("删除设备失败");
            }
            if (!response.getBody().success) {
                throw new BaseException("删除设备失败");
            }
        }

    }

    /**
     * 通过产品key注册设备，返回设备信息
     * 通过产品key获取产品信息
     * 组装设备信息与产品信息到Device
     *
     * @param dto
     */
    @Override
    public void registerDevice(DeviceDto dto) {
        //1.查询数据库，设备名称是否重复
        LambdaQueryWrapper<Device> queryWrapper = Wrappers.<Device>lambdaQuery()
                .eq(Device::getDeviceName, dto.getDeviceName());
        long count = count(queryWrapper);
        if (count > 0) {
            throw new BaseException("设备名称重复");
        }
        //2.根据产品key去IOT新增设备
        RegisterDeviceRequest registerDeviceRequest = dto.getRegisterDeviceRequest();
        registerDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        RegisterDeviceResponse response;
        try {
            response = client.registerDevice(registerDeviceRequest);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 注册设备，调用失败");
        }
        // 判断保存设备到iot平台是否成功
        if (!response.getBody().success) {
            throw new BaseException(response.getBody().getErrorMessage());
        }
        //查询产品数据
        QueryProductRequest queryProductRequest = new QueryProductRequest();
        queryProductRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        queryProductRequest.setProductKey(dto.getProductKey());
        QueryProductResponse queryProductResponse;
        try {
            queryProductResponse = client.queryProduct(queryProductRequest);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询产品，调用失败");
        }
        if (!queryProductResponse.getBody().success) {
            throw new BaseException("物联网接口 - 查询产品，调用失败");
        }
        // 设置产品名称到设备对象
        Device device = BeanUtil.toBean(dto, Device.class);
        device.setProductName(queryProductResponse.getBody().getData().getProductName());
        // 物理位置
        if (device.getLocationType().equals(0)) {
            device.setPhysicalLocationType(-1);
        }
        // 设备iot_id
        device.setIotId(response.getBody().getData().getIotId());
        try {
            deviceMapper.insertDevice(device);
        } catch (Exception e) {
            // 删除iot中的设备
            DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
            deleteDeviceRequest.setDeviceName(device.getDeviceName());
            deleteDeviceRequest.setProductKey(device.getProductKey());
            deleteDeviceRequest.setIotId(device.getIotId());
            deleteDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
            try {
                client.deleteDevice(deleteDeviceRequest);
            } catch (Exception ex) {
                throw new BaseException("物联网接口 - 删除设备，调用失败");
            }
            throw new BaseException("该老人/位置已绑定该产品，请重新选择");
        }
    }

    /**
     * 通过产品key与设备的IOTID查询设备详情
     * 查询数据库查询设备信息
     * 组装DeviceVO返回
     *
     * @param dto
     * @return
     */
    @Override
    public DeviceVo queryDeviceDetail(DeviceDto dto) {
        String productKey = dto.getProductKey();
        String iotId = dto.getIotId();
        // 查询设备详情,iotid,productkey
        QueryDeviceDetailRequest queryDeviceDetailRequest = new QueryDeviceDetailRequest();
        queryDeviceDetailRequest.setIotId(iotId);
        queryDeviceDetailRequest.setProductKey(productKey);
        queryDeviceDetailRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryDeviceDetailResponse response;
        try {
            response = client.queryDeviceDetail(queryDeviceDetailRequest);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询设备详情失败");
        }
        if (!response.getBody().success) {
            throw new BaseException("物联网接口 - 查询设备详情失败");
        }
        // 查询数据库设备信息
        Device device = getOne(Wrappers.<Device>lambdaQuery()
                .eq(Device::getIotId, dto.getIotId()));
        DeviceVo deviceVo = BeanUtil.toBean(device, DeviceVo.class);
        //合并信息
        QueryDeviceDetailResponseBody.QueryDeviceDetailResponseBodyData data = response.getBody().getData();
        BeanUtil.copyProperties(data, deviceVo, CopyOptions.create().ignoreNullValue());
        return deviceVo;
    }

    /**
     * 通过IotInstanceId，productKey
     * 查看指定产品的已发布物模型中的功能定义详情
     *
     * @param request
     * @return
     */
    @Override
    public AjaxResult queryThingModelPublished(QueryThingModelPublishedRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryThingModelPublishedResponse response;
        try {
            response = client.queryThingModelPublished(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询物模型数据，调用失败");
        }
        if (!response.getBody().success) {
            throw new BaseException(response.getBody().getErrorMessage());
        }

        return AjaxResult.success(response.getBody().getData());
    }

    /**
     * 通过IotInstanceId，productKey,deviceName
     * 查询设备属性状态
     *
     * @param request
     * @return
     */
    @Override
    public AjaxResult queryDevicePropertyStatus(QueryDevicePropertyStatusRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryDevicePropertyStatusResponse response;
        try {
            response = client.queryDevicePropertyStatus(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询设备属性状态，调用失败");
        }
        if (!response.getBody().success) {
            throw new BaseException(response.getBody().getErrorMessage());
        }

        return AjaxResult.success(response.getBody().getData());
    }
}
